//
//  GDButton.m
//  Gunterapple
//
//  Created by 热带雨林 on 2021/1/25.
//  Copyright © 2021 热带雨林. All rights reserved.
//

#import "GDButton.h"

@interface GDButton ()

@property (nonatomic, strong) NSString *titleName;
@property (nonatomic, assign) CGFloat fontSize;
@property (nonatomic, strong) NSString *imageName;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;

@end

@implementation GDButton



//此处不能自定义方法，frame没有办法确定
//- (instancetype)creatGDButtonWithTitleName:(NSString *)title withFontSize:(CGFloat)fontSize withImageName:(NSString *)imageName withWidth:(CGFloat)width withHeight:(CGFloat)height withOriginX:(CGFloat)x withOriginY:(CGFloat)y{
//    
//    UIFont *font = [UIFont systemFontOfSize:fontSize];
//    CGRect rect = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, 30) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : font}  context:nil];
//    return self;
//}
//系统自带方法
//注意if else 问题 不要不写
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
    
    if (!CGRectIsEmpty(self.titleRect) && !CGRectEqualToRect(self.titleRect, CGRectZero)) {
        return self.titleRect;
    } else {
        return [super titleRectForContentRect:contentRect];
    }
}
- (CGRect)imageRectForContentRect:(CGRect)contentRect {
    
    if (!CGRectIsEmpty(self.imageRect)&&!CGRectEqualToRect(self.imageRect, CGRectZero)) {
        return self.imageRect;
    } else {
        return [super imageRectForContentRect:contentRect];
    }
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    BOOL hasSetTitleRect = !(CGRectIsEmpty(self.titleRect)) || CGRectEqualToRect(self.titleRect, CGRectZero);
    BOOL hasSetImageRect = !(CGRectIsEmpty(self.imageRect)) || CGRectEqualToRect(self.imageRect, CGRectZero);

    if(hasSetImageRect || hasSetTitleRect){
        CGRect rect = self.frame;
        CGRect currentRect = CGRectUnion(hasSetImageRect ? self.imageRect : CGRectZero, hasSetTitleRect ? self.titleRect : CGRectZero);
        rect.size.width = currentRect.size.width + currentRect.origin.x * 2;
        rect.size.height = currentRect.size.height + currentRect.origin.y * 2;
        self.frame = rect;
    }
}

#pragma mark - 增大button点击范围
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
    
    CGRect bounds = self.bounds;
    //若热区域小于44*44 放大热区 则保持原区域大小不变
    CGFloat widthDetal = MAX(44.0 - bounds.size.width, 0);
    CGFloat heightDetal =  MAX(44.0 - bounds.size.height, 0);
    bounds = CGRectInset(bounds, -0.5 * widthDetal, -0.5 * heightDetal);
    return  CGRectContainsPoint(bounds, point);
    
}

@end
